package com.changhong.framework.sdfs.namenode.server.transport;

import com.changhong.framework.sdfs.namenode.server.builder.NameNodeBuilder;
import com.changhong.framework.sdfs.namenode.server.config.NameNodeConfig;
import com.changhong.framework.sdfs.namenode.server.directory.FileManagerSystem;
import com.changhong.framework.sdfs.namenode.server.register.DataNodeRegistry;
import com.changhong.framework.sdfs.rpc.rpcservice.NameNodeServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * RPC服务
 * @author Summer
 */
public class NameNodeRpcServer {

    private static final Logger logger = LoggerFactory.getLogger(NameNodeRpcServer.class);
    private Server server = null;

    /**
     * 配置管理组件
     */
    private final NameNodeConfig nameNodeConfig;

    public NameNodeRpcServer() {
        this.nameNodeConfig=NameNodeBuilder.getInstance(NameNodeConfig.class);
    }

    public void start() throws IOException {
        server = ServerBuilder
                .forPort(nameNodeConfig.getRpcServerPort())
                .addService(NameNodeServiceGrpc.bindService(new NameNodeRpcServiceImpl()))
                .build()
                .start();
        logger.debug("NameNodeRpcServer启动，监听端口号：" + nameNodeConfig.getRpcServerPort());
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                stopServer();
            }
        });
    }

    public void stopServer() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
